
import { createRouter, createWebHashHistory, RouteRecordRaw, useRouter } from "vue-router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import outsideLayout from "./outsideLayout";
import { whiteNameList } from "./constant";
import { useUserStore } from "@/store/modules/user";
import { Storage } from "@/utils/Storage";
import { useDynamicRouting } from "../store/modules/dynamicRouting";
import { itemForm } from "@components/draggable/clounms/accessPath/accessPathSettings/formConfig";
import { Console, log } from "console";
// import { createRouterGuards } from "./router-guards";


// 配置NProgress进度条选项
NProgress.configure({ easing: "ease", speed: 500 });

const routes: Array<RouteRecordRaw | any> = [
  {
    path: "/content",
    alias: ['/', '/index'],
    component: () => import("@/layouts/index.vue"),
    name: 'content',
    redirect: "/content/index",
  },
  // Layout之外的路由
  ...outsideLayout,
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
}) as any;
export function resetRouter() {
  router.getRoutes().forEach((route: any) => {
    const { fullPath } = route;
    if (fullPath && !whiteNameList.some((n) => n === fullPath)) {
      router.hasRoute(fullPath) && router.removeRoute(fullPath);
    }
  });
}

let arr = []
// 递归删除数组中符合条件的元素，并返回新数组
const handleData = (array: any[], pid: any) => {
  return array.reduce((prev, item, index) => {
    if (item.menuType == 2) {
      return prev
    }
    prev[index] = item;
    prev[index].realPid = pid;
    if (item.children) {
      prev[index].children = handleData(item.children, item.component.includes('layouts') ? item.id : item.realPid);
    }
    prev = prev.filter((item: any) => item)
    return prev
  }, [])
}
const treeToTile = (treeData: any[], childKey = "children") => {
  //用于拍平数据， 可考虑公用global.ts中使用
  const arr: any[] = [];
  const expanded = (data: any[], com: any) => {
    if (data && data.length > 0) {
      data
        .filter((d) => d)
        .forEach((e) => {
          if (com) {
            if (!com.includes('layouts')) {
              arr.push(e);
            } else {

            }
          } else {
            arr.push(e);
          }
          expanded(e[childKey] || [], e.component);
        });
    }
  };
  expanded(treeData, '');
  return arr;
};
const handleChild = (array: any[], arr: any[]) => {
  array.forEach((item: any) => {
    arr.forEach((data: any) => {
      if (data.realPid == item.id) {
        item.children.push(data);
        item.children.forEach((child: any) => {
          if (child.id == data.parentId) {
            child.children = child.children.filter((c: any) => !(c.id == data.id))
          }
        })
      }
    })
  });
  array.forEach((item: any, index: number) => {
    if (item.realPid && item.parentId != item.realPid) {
      array.splice(index, 1)
    }
  })
}
const addRouteAll = (menu: any[], viewsComponent: any, layoutsComponent: any) => {  //RoleMenu就是接口返回的数据的类型
  menu.forEach(item => {
    // if (item.routePath) {
    //   addRouteItem(item)
    if (item.menuType != 2) {
      item.path = item.routePath;
      item.key = item.routePath;
      item.name = item.menuName;
      item.entryPage = item.entryPage || '';
      if (item.component) {
        if (viewsComponent['../c-views/' + item.component + '.vue'] || layoutsComponent['../' + item.component + '.vue']) {
          item.component = viewsComponent['../c-views/' + item.component + '.vue'] || layoutsComponent['../' + item.component + '.vue']
        } else {
        }
      }
      try {
        item.meta = eval('(' + item.meta + ')');
        item.meta.id = item.id;
      } catch (err) {
        item.meta = { id: item.id }
      }

      if (!item.component) {
        delete item.component
      }
      if (!item.redirect) {
        delete item.redirect
      }

      if (item.children && item.children.length > 0 && item.menuType != 2) {
        item.redirect = item.children && !item.parentId ? item.children[0]?.routePath : undefined;
        addRouteAll(item.children, viewsComponent, layoutsComponent);
      }
    }
  })
}
export async function setupRouter(app: any) {
  // 创建路由守卫
  //createRouterGuards(router, whiteNameList);

  app.use(router);

  // 路由准备就绪后挂载APP实例
  await router.isReady();
}

router.beforeEach((to: any, from: any, next: any) => {
  const userStore = useUserStore();
  if (to.path == '/login') {
    next()
  } else {
    if (Storage.get('ACCESS_TOKEN')) {
      const viewsComponent: Record<string, any> = import.meta.glob("../c-views/**/*.vue");
      const layoutsComponent: Record<string, any> = import.meta.glob("../layouts/**/*.vue");
      let routerList = JSON.parse(JSON.stringify(userStore.userInfo.menues));
      handleData(routerList, '');
      let routers = treeToTile(routerList);
      routers.forEach((item: any, index: number) => {
        if (item.menuType == 2) {
          routers.splice(index, 1)
        }
      })
      handleChild(routers, JSON.parse(JSON.stringify(routers)));
      if (!Storage.get("isLogin")) {
        addRouteAll(routers, viewsComponent, layoutsComponent);
        //setTimeout(() => {
          routers.forEach((item: any) => {
            router.addRoute(item);
          });
          // console.log(location.href, '前置守卫:location.href');
          if(location.href.includes("ken")) {
            const start: any = location.href.indexOf("ken=") + 4
            const ken = location.href.substring(start)
            sessionStorage.ken = ken
          } else {
            // sessionStorage.removeItem('ken')
          }
        let path = sessionStorage.user ? (Storage.get('selectFullPath') && Storage.get('selectFullPath') != '/login' ? Storage.get('selectFullPath') : '/') : '/login';
        next({ path: path, query: Storage.get('selectPathQuery') || {} })
        //}, 40)
      }
      next();
      Storage.set("isLogin", true)
    } else {
      next({ path: '/login' })
    }

  }

});

export default router;
